package com.kele.controller;


import com.alibaba.fastjson.JSON;
import com.kele.entity.Login;
import com.kele.entity.LoginVo;
import com.kele.service.impl.LoginServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kele
 * @since 2022-01-08
 */
@RestController
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;

    @PostMapping("/testLogin")
    public String testLogin (@RequestBody LoginVo loginVo, HttpServletRequest request) {
        log.info("===================>>>>>>, {}", JSON.toJSONString(loginVo));
        Login login = loginService.userLogin(loginVo);
        log.info("login-----------> {}",login);
        if (login==null)
        {
            return "用户名或者密码错误";
        }else if(login.getToken() == null){
            log.info("没有token,生成token");
            String token = UUID.randomUUID().toString();
            log.info("token===============> {}",token);
            int result = loginService.insertToken(token, login.getId());
            if(result>0){
                return  "用户登录成功，token是：" + token;
            }
        } else {
            String token = UUID.randomUUID().toString();
            log.info("token===============> {}",token);
            int result = loginService.insertToken(token, login.getId());
            if(result>0){
                return  "用户登录成功，token是：" + token;
            }
        }
        return JSON.toJSONString(login);
    }
}

